import 'package:get/get.dart';
import '../services/api_service.dart';
import '../models/prompt_model.dart';
import '../services/logger_service.dart';

/// API 仓库 - API Repository
/// 负责处理与远程服务器的数据交互
class ApiRepository extends GetxService {
  static ApiRepository get to => Get.find();

  late ApiService _apiService;

  @override
  Future<void> onInit() async {
    super.onInit();
    _apiService = ApiService.to;
    LoggerService.info('API 仓库初始化完成 - API Repository initialized');
  }

  /// 同步 Prompt 到服务器 - Sync Prompt to Server
  Future<bool> syncPromptToServer(PromptModel prompt) async {
    try {
      final response = await _apiService.post(
        '/prompts',
        data: prompt.toJson(),
      );
      
      if (response.statusCode == 200 || response.statusCode == 201) {
        LoggerService.info('Prompt 同步成功 - Prompt synced successfully: ${prompt.title}');
        return true;
      }
      
      LoggerService.warning('Prompt 同步失败 - Prompt sync failed: ${response.statusCode}');
      return false;
    } catch (e) {
      LoggerService.error('Prompt 同步异常 - Prompt sync exception', error: e);
      return false;
    }
  }

  /// 从服务器获取 Prompts - Get Prompts from Server
  Future<List<PromptModel>> getPromptsFromServer({
    int page = 1,
    int limit = 20,
    String? category,
    List<String>? tags,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'page': page,
        'limit': limit,
      };
      
      if (category != null) queryParams['category'] = category;
      if (tags != null && tags.isNotEmpty) queryParams['tags'] = tags.join(',');

      final response = await _apiService.get(
        '/prompts',
        queryParameters: queryParams,
      );

      if (response.statusCode == 200) {
        final data = response.data.data as Map<String, dynamic>;
        final promptsData = data['prompts'] as List<dynamic>;
        
        final prompts = promptsData
            .map((json) => PromptModel.fromJson(json as Map<String, dynamic>))
            .toList();
            
        LoggerService.info('从服务器获取 ${prompts.length} 个 Prompts - Retrieved ${prompts.length} prompts from server');
        return prompts;
      }
      
      LoggerService.warning('获取 Prompts 失败 - Failed to get prompts: ${response.statusCode}');
      return [];
    } catch (e) {
      LoggerService.error('获取 Prompts 异常 - Get prompts exception', error: e);
      return [];
    }
  }

  /// 更新服务器上的 Prompt - Update Prompt on Server
  Future<bool> updatePromptOnServer(PromptModel prompt) async {
    try {
      final response = await _apiService.put(
        '/prompts/${prompt.id}',
        data: prompt.toJson(),
      );
      
      if (response.statusCode == 200) {
        LoggerService.info('Prompt 更新成功 - Prompt updated successfully: ${prompt.title}');
        return true;
      }
      
      LoggerService.warning('Prompt 更新失败 - Prompt update failed: ${response.statusCode}');
      return false;
    } catch (e) {
      LoggerService.error('Prompt 更新异常 - Prompt update exception', error: e);
      return false;
    }
  }

  /// 从服务器删除 Prompt - Delete Prompt from Server
  Future<bool> deletePromptFromServer(String promptId) async {
    try {
      final response = await _apiService.delete('/prompts/$promptId');
      
      if (response.statusCode == 200 || response.statusCode == 204) {
        LoggerService.info('Prompt 删除成功 - Prompt deleted successfully: $promptId');
        return true;
      }
      
      LoggerService.warning('Prompt 删除失败 - Prompt deletion failed: ${response.statusCode}');
      return false;
    } catch (e) {
      LoggerService.error('Prompt 删除异常 - Prompt deletion exception', error: e);
      return false;
    }
  }

  /// 搜索服务器上的 Prompts - Search Prompts on Server
  Future<List<PromptModel>> searchPromptsOnServer(String query, {
    List<String>? categories,
    List<String>? tags,
    int page = 1,
    int limit = 20,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'q': query,
        'page': page,
        'limit': limit,
      };
      
      if (categories != null && categories.isNotEmpty) {
        queryParams['categories'] = categories.join(',');
      }
      if (tags != null && tags.isNotEmpty) {
        queryParams['tags'] = tags.join(',');
      }

      final response = await _apiService.get(
        '/prompts/search',
        queryParameters: queryParams,
      );

      if (response.statusCode == 200) {
        final data = response.data.data as Map<String, dynamic>;
        final promptsData = data['prompts'] as List<dynamic>;
        
        final prompts = promptsData
            .map((json) => PromptModel.fromJson(json as Map<String, dynamic>))
            .toList();
            
        LoggerService.info('搜索到 ${prompts.length} 个 Prompts - Found ${prompts.length} prompts');
        return prompts;
      }
      
      LoggerService.warning('搜索失败 - Search failed: ${response.statusCode}');
      return [];
    } catch (e) {
      LoggerService.error('搜索异常 - Search exception', error: e);
      return [];
    }
  }

  /// 检查服务器连接状态 - Check Server Connection Status
  Future<bool> checkServerConnection() async {
    try {
      return await _apiService.checkConnection();
    } catch (e) {
      LoggerService.error('服务器连接检查失败 - Server connection check failed', error: e);
      return false;
    }
  }

  /// 用户认证 - User Authentication
  Future<bool> authenticate(String username, String password) async {
    try {
      final response = await _apiService.post(
        '/auth/login',
        data: {
          'username': username,
          'password': password,
        },
      );

      if (response.statusCode == 200) {
        final data = response.data.data as Map<String, dynamic>;
        final token = data['token'] as String;
        
        // 设置认证令牌 - Set authentication token
        _apiService.setAuthToken(token);
        
        LoggerService.info('用户认证成功 - User authentication successful');
        return true;
      }
      
      LoggerService.warning('用户认证失败 - User authentication failed: ${response.statusCode}');
      return false;
    } catch (e) {
      LoggerService.error('用户认证异常 - User authentication exception', error: e);
      return false;
    }
  }

  /// 用户登出 - User Logout
  Future<void> logout() async {
    try {
      await _apiService.post('/auth/logout');
      _apiService.clearAuthToken();
      LoggerService.info('用户登出成功 - User logout successful');
    } catch (e) {
      LoggerService.error('用户登出异常 - User logout exception', error: e);
      _apiService.clearAuthToken();
    }
  }
}